﻿/*
 * KLF Headless Browser
 * Written by Kris Oye <kristianoye@gmail.com>
 * Copyright (C) 2011-2012.  All rights reserved.
 */
namespace KLF.Lib.Browser.DOM
{
    #region Using Statements

    using System.Collections.Generic;
    using System;

    #endregion

    internal class StringLookup
    {
        /// <summary>
        /// A collection of observed strings.
        /// </summary>
        private static List<string> StringTable { get; set; }

        /// <summary>
        /// The index into the string table.
        /// </summary>
        internal int StringIndex { get; set; }

        /// <summary>
        /// The static constructor to initialize the StringTable
        /// </summary>
        static StringLookup()
        {
            StringTable = new List<string>();
        }

        /// <summary>
        /// "Constructs" a new string value.
        /// </summary>
        /// <param name="value"></param>
        public StringLookup(string value)
        {
            StringIndex = StringTable.IndexOf(value);

            if (StringIndex < 0)
            {
                StringTable.Add(value);
                StringIndex = StringTable.IndexOf(value);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public static string Get(int index)
        {
            if (index < 0 || index >= StringTable.Count)
                return "";
            else
                return StringTable[index];
        }

        /// <summary>
        /// Returns the underlying value of the string.
        /// </summary>
        public string Value
        {
            get
            {
                return (string)StringTable[StringIndex].Clone();
            }
        }

        /// <summary>
        /// Returns an empty string in DOMString format.
        /// </summary>
        public StringLookup Empty
        {
            get
            {
                return new StringLookup("");
            }
        }

        /// <summary>
        /// Returns true if the StringLookup is null or underlying value empty.
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        internal static bool IsNullOrEmpty(StringLookup str)
        {
            return (str == null || String.IsNullOrEmpty(str.Value));
        }

        /// <summary>
        /// Returns the underlying string value of empty if the instance is null.
        /// </summary>
        /// <param name="_type"></param>
        /// <returns></returns>
        internal static string GetValue(StringLookup _type)
        {
            return (_type == null ? "" : _type.Value);
        }
    }
}
